import socket
from threading import Thread
from datetime import datetime

HOST = '127.0.0.1'
PORT = 8888
client_number = 10
client = {}
addresses = {}
time_format = "%H:%M:%S"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))


def client_handle_in(conn, address):
    nickname = conn.recv(1024).decode('utf8').strip()
    welcome = f'欢迎 { nickname } 加入聊天\n'
    client[conn] = nickname
    broadcast(bytes(welcome, 'utf8'))
    while True:
        try:
            msg = conn.recv(1024)
            broadcast(msg, nickname+':')
        except:
            del client[conn]
            broadcast(bytes(f'{ nickname} 离开聊天室', 'utf8'))


def broadcast(msg, nickname=''):
    msg_time = datetime.now().strftime(time_format)
    for conn_obj in client:
        print('这条消息的发送用户为：' + nickname)
        conn_obj.send(bytes(msg_time + ' ' + nickname, 'utf8') + msg)


if __name__ == '__main__':
    s.listen(client_number)
    print('服务器已经开始监听...')
    while True:
        conn, addr = s.accept()
        print(addr, '已经连接上服务器...')
        conn.send('你已连接聊天服务器成功，请输入你的昵称进行聊天\n'.encode('utf8'))
        addresses[conn] = addr
        Thread(target=client_handle_in, args=(conn, addr)).start()
